<template>
  <div class="app-container">
    <van-nav-bar :title="title" left-arrow fixed @click-left="back">
      <template v-if="isAddNew" #right>
        <van-icon name="plus" csize="18" @click="getNewLine(1)" />
      </template>
    </van-nav-bar>
    <div class="container-box">
      <div class="descBox" :hidden="isShowHead" v-html="descHTML"></div>
      <div class="form-container">
        <vantForm v-for="(item,index) in formEl" ref="vanForm" :key="index" :rules="rules[index]" :input-vail="true">
          <template slot="items">
            <dynamic-form :idx="index" :form-el="item.data" :list-data="item" class="form-box" :config="formConfig" @eventFn="onClickBtnFn" />
          </template>
        </vantForm>
      </div>
      <div class="descBox" :hidden="isShowFoot" v-html="descHTML"></div>
      <div class="space-line"></div>
      <div class="opration-box flex">
        <!-- v-if="isAddNew" -->
        <!-- <van-button v-if="isAddNew" class="btn-cls" round block type="default" @click="submitForm">
          + 校验
        </van-button>
        <van-button v-if="isAddNew" class="btn-cls" round block type="default" @click="getNewLine(1)">
          + 新增
        </van-button>-->
        <!-- <div class="formSubmitBtn"> -->
        <van-button class="btn-full" :class="{'btn-full':!isAddNew}" block type="info" @click="saveData(1)">
          保存
        </van-button>
        <!-- </div> -->
      </div>
    </div>
  </div>
</template>
<script>
import DynamicForm from '@/components/d-form/DynamicForm'
import VantForm from '@/components/d-form/form-el/EleValidate.vue'
import { homeApi } from '@/api/home.js'
import store from '../storage'
import { Toast } from 'vant'
import { ConsoleLogger } from '@microsoft/signalr/dist/esm/Utils'

export default {
  name: 'InputForm',
  components: {
    DynamicForm,
    VantForm
  },
  data () {
    return {
      formConfig: {
        isShowCloseBtn: true
      },
      listKeys: [],
      listStore: {},
      tbObj: {}, // 入职清单数据集
      keyid: '',
      uuid: '',
      title: '',
      isAddNew: false,
      formEl: [],
      rules: {
        // 'userName': { required: true },
        // 'phone': { regExp: /^(1\d{10})$/, required: true },
        // 'pwd': { regExp: /^(\w){6,20}$/, required: true },
        // 'confirmPwd': {
        //   required: true,
        //   handleVailFun: val => { return val === this.reqParam.pwd }
        // }
      }
    }
  },
  computed: {
    isShowHead() {
      return this.tbObj.position === 'F'
    },
    isShowFoot() {
      return this.tbObj.position === 'H'
    },
    descHTML() {
      return this.tbObj.description
    }
  },
  watch: {
    formEl: {
      handler (arr) {
        arr.some((formItem, formIndex) => {
          this.$set(this.rules, formIndex, {})
          const formData = formItem.data
          formData.some(formGroups => {
            const list = formGroups.list
            list.some(item => {
              if (item.required) {
                const key = item.key
                // console.log(key, item.label)
                // if (key === 'A0177') {
                //   debugger
                // }
                this.rules[formIndex][key] = {
                  required: true
                }
              }
            })
          })
        })

        if (this.isAddNew) {
          this.formConfig.isShowCloseBtn = arr.length > 1
        } else {
          this.formConfig.isShowCloseBtn = false
        }
      },
      deep: true
    }
  },
  created () {
    var $this = this
    $this.keyid = this.$route.query.key
    $this.title = this.$route.query.title
    $this.uuid = this.$route.query.uuid
    // $this.listStore = store.getkey('listData') || {}
    $this.listKeys = store.getkey($this.keyid) || {}
    /* $this.listKeys.forEach(kk => {
      $this.listStore.push({
        keyid: kk,
        data: store.getkey(kk)
      })
    }) */

    // 取得入职清单，取得入职表结构的参数
    var list = store.get()
    list.forEach(el => {
      if (el.keyid === $this.keyid) {
        $this.tbObj = el
      }
    })
    debugger
    $this.getNewLine(0)
    $this.getIsAddNew()
  },
  methods: {
    submitForm () {
      let num = 0
      this.$refs.vanForm.map(dom => {
        console.log('dom', dom)
        const flag = dom.allVail()
        if (flag) {
          num++
        }
      })
      // 只有全部通过，才算通过
      if (num === this.$refs.vanForm.length) {
        this.$notice.tip(1, '校验通过')
      }
    },
    /**
     * 更多功能 触发
     * clickMode: 0.方法 1.url 2.弹窗
     */
    onClickBtnFn (item) {
      // debugger
      if (item.clickMode === 0) {
        this[item.fnName](...arguments)
      } else if (item.clickMode === 1) {
        this.$router.push({ name: item.fnName })
      } else {
        this[item.fnName] = true
      }
    },
    delFn (item) {
      this.$notice.confirm('提示', '确定要删除吗？', (bool) => {
        if (bool) {
          const { idx } = item
          // console.log(...arguments)
          this.formEl.splice(idx, 1)
          this.saveData(0)
        }
      })
    },
    // 取得key的组别是否可以输入多条记录
    getIsAddNew: function () {
      const _this = this
      const keyid = _this.keyid
      const list = store.get()
      // console.log('list', list)
      list.some((v, index) => {
        if (v.keyid === keyid) {
          _this.isAddNew = v.multiRow
          // debugger
          return true
        }
      })
    },
    // 获取form表单数据
    /**
     * @params {Number} num 0.初始化调用 1.手动调用
     */
    getNewLine (num) {
      const _this = this
      // const res = _this.listStore[_this.key]
      const res = store.getkey(_this.keyid)
      // debugger
      // console.log('listStore-res：', res)
      if (num === 0 && !store.isNull(res)) {
        _this.formEl = res.data
        return res
      }
      console.log('uuid=' + _this.uuid)
      const params = {
        keyid: _this.keyid,
        uid: _this.uuid
      }

      homeApi.input(null, params).then(res => {
        if (res.code === 200) {
          _this.formEl.push({ index: _this.formEl.length, data: res.data, canDel: true, isFinish: false })
          _this.saveData(0)
        } else {
          throw new Error(JSON.stringify(res))
        }
      }).catch(err => {
        console.error('err', err)
      })
      // const url = window.g.WEBAPI_HOST_URL + 'api/v1/Forms/input?keyid=' + _this.keyid
      // request.post(url).then(response => {
      // })
    },
    showData: function () {
      Toast(this.item.value)
    },
    // 0.程序自动调用，1.手动触发
    saveData: function (num) {
      var listStore = store.getkey(this.keyid) || {}
      if (num === 1) {
        let flagNum = 0
        this.$refs.vanForm.map(dom => {
          // console.log('dom', dom)
          const flag = dom.allVail()
          if (flag) {
            flagNum++
          }
        })

        // 只有全部通过，才算通过
        if (flagNum !== this.$refs.vanForm.length) {
          return
          // this.$notice.tip(1, '校验通过')
        }

        this.formEl.forEach(el => {
          el.isFinish = true
        })
        listStore.state = true
      } else {
        this.formEl.isFinish = false
        listStore.state = false
      }

      /* var listStore = store.getkey('listData') || {}
      if (!listStore[this.keyid]) {
        listStore[this.keyid] = {}
      }
      // this.formEl.isFinish = true
      listStore[this.keyid].data = this.formEl
      listStore[this.keyid].state = true
      store.setkey('listData', listStore) */
      debugger
      // console.log('formEl=')
      // console.log(this.formEl)
      listStore.data = this.formEl
      store.setkey(this.keyid, listStore)

      if (num === 1) {
        this.back() // 返回上一页
      }
    },
    back () {
      this.$router.go(-1)
    }
  }
}
</script>
<style lang="less" scoped>
.app-container {
  margin: 0 auto;
  width: 100%;
  height: 100%;
  background: #fafafa;
}

ul1 {
  list-style: disc;
  padding: 3px 15px;
  background: #fafafa;
}
// $btnH: 60px;
// .form-container {
//   min-height: 50vh;
//   padding-bottom: $btnH + 10px;
// }
// .opration-box {
//   position: fixed;
//   bottom: 0;
//   left: 0;
//   margin-top: 30px;
//   width: 100%;
//   height: $btnH;
//   background: #fff;
//   border-top: 1px solid #eee;
//   box-shadow: 0px -3px 20px 0px #bbb;
//   justify-content: space-around;
//   .btn-cls {
//     width: 45%;
//     box-shadow: 0 0px 4px 0 #bbb;
//   }
// }
</style>
